<template>
  <a-layout class="grid-container">
    <knowledge-sidebar @select="handleFolderSelect" />
    <div class="table-page">
      <GiTable title="知识库管理管理" row-key="id" :data="dataList" :columns="columns" :loading="loading"
        :scroll="{ x: '100%', y: '100%', minWidth: 800 }" :pagination="pagination" :disabled-tools="['size']"
        :disabled-column-keys="['name']" @refresh="search" :row-selection="rowSelection">
        <template #toolbar-left>
          <a-input v-model="queryForm.fileName" placeholder="请输入文件名" allow-clear @change="search">
            <template #prefix><icon-search /></template>
          </a-input>
          <!-- <a-input v-model="queryForm.physicalPath" placeholder="请输入物理存储路径" allow-clear @change="search">
          <template #prefix><icon-search /></template>
        </a-input>
        <a-input v-model="queryForm.logicalPath" placeholder="请输入逻辑文件夹路径" allow-clear @change="search">
          <template #prefix><icon-search /></template>
        </a-input>
        <a-input v-model="queryForm.fileType" placeholder="请输入文件类型" allow-clear @change="search">
          <template #prefix><icon-search /></template>
        </a-input>
        <a-input v-model="queryForm.createdBy" placeholder="请输入创建者" allow-clear @change="search">
          <template #prefix><icon-search /></template>
        </a-input>
        <a-input v-model="queryForm.createdAt" placeholder="请输入创建时间" allow-clear @change="search">
          <template #prefix><icon-search /></template>
        </a-input>
        <a-input v-model="queryForm.updatedAt" placeholder="请输入更新时间" allow-clear @change="search">
          <template #prefix><icon-search /></template>
        </a-input>
        <a-input v-model="queryForm.createUser" placeholder="请输入创建人" allow-clear @change="search">
          <template #prefix><icon-search /></template>
        </a-input>
        <a-input v-model="queryForm.createTime" placeholder="请输入创建时间" allow-clear @change="search">
          <template #prefix><icon-search /></template>
        </a-input> -->
          <a-button @click="reset">
            <template #icon><icon-refresh /></template>
            <template #default>重置</template>
          </a-button>
        </template>
        <template #toolbar-right>
          <a-button v-permission="['knowledge:knowledge:deepseek']" type="primary" @click="onAsk">
            <!-- <template #icon><icon-plus /></template> -->
            <template #default>问问deepseek</template>
          </a-button>
          <a-button v-permission="['knowledge:knowledge:add']" type="primary" @click="onAdd">
            <template #icon><icon-plus /></template>
            <template #default>新增</template>
          </a-button>
          <!-- <a-button v-permission="['knowledge:knowledge:export']" @click="onExport">
            <template #icon><icon-download /></template>
            <template #default>导出</template>
          </a-button> -->
        </template>
        <template #action="{ record }">
          <a-space>
            <a-link v-permission="['knowledge:knowledge:detail']" title="详情" @click="onDetail(record)">详情</a-link>
            <!-- <a-link v-permission="['knowledge:knowledge:update']" title="修改" @click="onUpdate(record)">修改</a-link> -->
            <a-link v-permission="['knowledge:knowledge:delete']" status="danger" :disabled="record.disabled"
              :title="record.disabled ? '不可删除' : '删除'" @click="onDelete(record)">
              删除
            </a-link>
            <a-link v-permission="['knowledge:knowledge:edit']" title="编辑" @click="onEdit(record)">
              编辑
            </a-link>
          </a-space>
        </template>
      </GiTable>

      <KnowledgeAddModal ref="KnowledgeAddModalRef" @save-success="handleRefresh" />
      <KnowledgeDetailDrawer ref="KnowledgeDetailDrawerRef" />
      <AskDeepseek ref="KnowledgeAskDeepseekRef" />
    </div>
  </a-layout>

</template>

<script setup lang="ts">
import KnowledgeAddModal from './KnowledgeAddModal.vue'
import KnowledgeDetailDrawer from './KnowledgeDetailDrawer.vue'
import KnowledgeSidebar from './KnowledgeSidebar.vue'
import { useDownload, useTable } from '@/hooks'
import { useDict } from '@/hooks/app'
import { isMobile } from '@/utils'
import has from '@/utils/has'
import {
  type
    KnowledgeResp,
  type
    KnowledgeQuery,
  deleteKnowledge,
  exportKnowledge,
  listKnowledge,
  listKnowledgeByFileName
} from '@/apis/knowledge/knowledge'
import type { TableInstanceColumns } from '@/components/GiTable/type'
import AskDeepseek from './AskDeepseek.vue'

defineOptions({ name: 'Knowledge' })

const queryForm = reactive<KnowledgeQuery>({
  fileName: undefined,
  physicalPath: undefined,
  logicalPath: undefined,
  fileType: undefined,
  createdBy: undefined,
  createdAt: undefined,
  updatedAt: undefined,
  createUser: undefined,
  createTime: undefined,
  sort: ['id,desc']
})

// const queryByFileName = async (fileName: string, parentFolderId: number) => {
//   const { data: dataList } = await listKnowledgeByFileName(fileName, parentFolderId);
// }

const {
  tableData: dataList,
  loading,
  pagination,
  search,
  handleDelete
} = useTable((page) => listKnowledge({ ...queryForm, ...page, isFolder: false }), { immediate: true })
const columns: TableInstanceColumns[] = [
  { title: '文件名', dataIndex: 'fileName', slotName: 'fileName' },
  // { title: '物理存储路径', dataIndex: 'physicalPath', slotName: 'physicalPath' },
  // { title: '逻辑文件夹路径', dataIndex: 'logicalPath', slotName: 'logicalPath' },
  // { title: '父文件夹ID', dataIndex: 'parentFolderId', slotName: 'parentFolderId' },
  { title: '文件大小（字节）', dataIndex: 'fileSize', slotName: 'fileSize' },
  { title: '文件类型', dataIndex: 'fileType', slotName: 'fileType' },
  // { title: '是否文件夹', dataIndex: 'isFolder', slotName: 'isFolder' },
  // { title: '创建者', dataIndex: 'createdBy', slotName: 'createdBy' },
  // { title: '创建时间', dataIndex: 'createdAt', slotName: 'createdAt' },
  { title: '更新时间', dataIndex: 'updatedAt', slotName: 'updatedAt' },
  // { title: '删除标记', dataIndex: 'isDeleted', slotName: 'isDeleted' },
  // { title: '创建人', dataIndex: 'createUser', slotName: 'createUser' },
  // { title: '创建时间', dataIndex: 'createTime', slotName: 'createTime' },
  // { title: '修改人', dataIndex: 'updateUser', slotName: 'updateUser' },
  // { title: '修改时间', dataIndex: 'updateTime', slotName: 'updateTime' },
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'action',
    width: 160,
    align: 'center',
    fixed: !isMobile() ? 'right' : undefined,
    show: has.hasPermOr(['knowledge:knowledge:detail', 'knowledge:knowledge:delete', 'knowledge:knowledge:edit'])
  }
]

// 新增响应式数据
const selectedFolderId = ref(null)
const selectedPhysicalPath = ref("")
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true
})

const handleRefresh = () => {
    search();
};

// 处理目录选择
const handleFolderSelect = (folderId: string, physicalPath: string) => {
  // console.log("physicalPath: ", physicalPath)
  selectedPhysicalPath.value = physicalPath
  selectedFolderId.value = folderId
  queryForm.parentFolderId = folderId
  queryForm.isFolder = false
  search()
}

// 重置
const reset = () => {
  queryForm.fileName = undefined
  // queryForm.physicalPath = undefined
  // queryForm.logicalPath = undefined
  // queryForm.fileType = undefined
  // queryForm.createdBy = undefined
  // queryForm.createdAt = undefined
  // queryForm.updatedAt = undefined
  // queryForm.createUser = undefined
  // queryForm.createTime = undefined
  search()
}

// 删除
const onDelete = (record: KnowledgeResp) => {
  return handleDelete(() => deleteKnowledge(record.id, record.physicalPath, record.isFolder), {
    content: `是否确定删除该条数据？`,
    showModal: true
  })
}

// 导出
const onExport = () => {
  useDownload(() => exportKnowledge(queryForm))
}

const KnowledgeAskDeepseekRef = ref<InstanceType<typeof AskDeepseek>>()
// 向大模型提问
const onAsk = () => {
  KnowledgeAskDeepseekRef.value?.onOpen(selectedPhysicalPath.value);
}

const KnowledgeAddModalRef = ref<InstanceType<typeof KnowledgeAddModal>>()
// 新增
const onAdd = () => {
  KnowledgeAddModalRef.value?.open(selectedPhysicalPath.value, selectedFolderId.value)
}

// 修改
// const onUpdate = (record: KnowledgeResp) => {
//   KnowledgeAddModalRef.value?.onUpdate(record.id)
// }

const KnowledgeDetailDrawerRef = ref<InstanceType<typeof KnowledgeDetailDrawer>>()
// 详情
const onDetail = (record: KnowledgeResp) => {
  KnowledgeDetailDrawerRef.value?.onOpen(record.id)
}

const onEdit = (record: KnowledgeResp) => {
  const user = {
    id: record.id,
    name: record.createUserString
  }
  window.open(`/knowledge/editor?fileName=${record.fileName}&user=${user}&physicalPath=${record.physicalPath}`, '_blank');
}
</script>

<style scoped>
.grid-container {
  display: grid;
  grid-template-columns: 280px 1fr;
  /* 侧边栏固定，表格自适应 */
  height: 20vh;
}

.knowledge-sidebar {
  grid-column: 1;
}

.arco-table {
  grid-column: 2;
  /* height: 70%; */
}
.table-page {
  height: 83%;
}
</style>
